//
//  ZZProgressHUD.m
//  ZZProgressHUD
//
//  Created by czz on 2018/5/22.
//  Copyright © 2018年 czz. All rights reserved.
//

#import "ZZProgressHUD.h"

static ZZProgressHUD *zzProgressHUD;


@implementation ZZProgressHUDModel
-(void)setText:(NSString *)text{
    if (text == NULL) {
        _text = @"";
        return;
    }
    if (text == nil) {
        _text = @"";
        return;
    }
    if (text == [NSNull class]) {
        _text = @"";
        return;
    }
    _text = text;
}
@end;

@implementation ZZProgressHUD{
    NSTimer *showTimer;
    NSTimer *dismissTimer;
    NSMutableArray *showArray;//数据结构@[@{@"text":text,@"state":state}] text:显示的文字 state:显示的状态
}

-(instancetype)init{
    self = [super init];
    if (self) {
        keyboardIsShow = NO;
        self.infoImage = [UIImage imageNamed:@"info"];
        self.errorImage = [UIImage imageNamed:@"error"];
        self.successImage = [UIImage imageNamed:@"success"];
        self.lineUpInterval = 1.;
        self.dismissInterval = 2.;
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(positionHUD:)
                                                     name:UIKeyboardWillHideNotification
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(positionHUD:)
                                                     name:UIKeyboardWillShowNotification
                                                   object:nil];
    }
    return self;
}
- (void)positionHUD:(NSNotification*)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    int height = keyboardRect.size.height;
    if (notification) {
        keyboardIsShow = NO;
        keyboardHeight = 0;
        if (notification.name == UIKeyboardWillShowNotification) {
            keyboardIsShow = YES;
            keyboardHeight = height;
        }
    }
//    NSLog(@"keyboard height : %d   notification name: %@",height,notification.name);
    [self updateShowViewCenter];
}
+(ZZProgressHUD *)shareZZProgressHUD{
    if (!zzProgressHUD) {
        zzProgressHUD = [[ZZProgressHUD alloc] init];
        
    }
    return zzProgressHUD;
}
-(UIView *)contentView{
    if (!_contentView) {
        _contentView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _contentView.alpha = 0.;
        _contentView.userInteractionEnabled = NO;
        [_contentView setBackgroundColor:[UIColor clearColor]];
        
    }
    return _contentView;
}
-(ZZProgressHUDShowView *)showView{
    if (!_showView) {
        _showView = [[ZZProgressHUDShowView alloc] initWithFrame:CGRectMake(100, 220, 200, 200)];
//        [_showView setDefaultBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.8]];
        [_showView setDefaultBackgroundColor:[UIColor clearColor]];
        _showView.titleLabel.numberOfLines = 0;
        _showView.title = @"加载中";
        _showView.userInteractionEnabled = NO;
        _showView.enabled = NO;
        _showView.imageLocation = ZZButtonImageLocation_Top;
        _showView.defaultImage = [UIImage imageNamed:@"info"];
        _showView.minSize = CGSizeEqualToSize(self.showMinSize, CGSizeZero) ? CGSizeMake(80, 80) : self.showMinSize;
        _showView.defaultTitleColor = [UIColor whiteColor];
        _showView.maxSize = CGSizeMake(200, 200);
        _showView.contentToBorderSpace = 10;
        _showView.titleLabel.textAlignment = NSTextAlignmentCenter;
        _showView.layer.masksToBounds = YES;
        _showView.layer.cornerRadius = 8.;
        [self.contentView addSubview:_showView];
        
    }
    return _showView;
}
-(void)setShowMinSize:(CGSize)showMinSize{
    _showMinSize = showMinSize;
    self.showView.minSize = _showMinSize;
}
-(void)setMinSizeWithoutLoading:(CGSize)minSizeWithoutLoading{
    _showMinSizeWithoutLoading = minSizeWithoutLoading;
}
-(void)setTextColor:(UIColor *)textColor{
    _textColor = textColor;
    self.showView.defaultTitleColor = _textColor;
    self.showView.defaultImage = [self.showView.defaultImage imageWithColor:_textColor];
    self.showView.activityIndicatorView.color = _textColor;
    if (_infoImage) {
        _infoImage = [_infoImage imageWithColor:_textColor];
    }
    if (_errorImage) {
        _errorImage = [_errorImage imageWithColor:_textColor];
    }
    if (_successImage) {
        _successImage = [_successImage imageWithColor:_textColor];
    }
}
-(void)setShowViewBlurEffect:(UIBlurEffect *)showViewBlurEffect{
    _showViewBlurEffect = showViewBlurEffect;
    self.showView.effectBgView.effect = _showViewBlurEffect;
}
-(void)setInfoImage:(UIImage *)infoImage{
    _infoImage = infoImage;
    if (self.textColor) {
        _infoImage = [_infoImage imageWithColor:self.textColor];
    }
}
-(void)setErrorImage:(UIImage *)errorImage{
    _errorImage = errorImage;
    if (self.textColor) {
        _errorImage = [_errorImage imageWithColor:self.textColor];
    }
}
-(void)setSuccessImage:(UIImage *)successImage{
    _successImage = successImage;
    if (self.textColor) {
        _successImage = [_successImage imageWithColor:self.textColor];
    }
}
-(void)show{
    if (showArray.count >= 1) {
        ZZProgressHUDModel *model = [showArray objectAtIndex:0];
        _showState = model.state;
        if (model.state == ShowViewState_Loading) {
            self.showView.spacing = 0;
            self.showView.minSize = CGSizeEqualToSize(self.showMinSize, CGSizeZero) ? CGSizeMake(80, 80) : self.showMinSize;
            self.showView.isLoading = YES;
            if (model.text.length == 0) {
                _showState = ShowViewState_Loading;
                [self.showView.activityIndicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
            }else{
                _showState = ShowViewState_LoadingText;
                [self.showView.activityIndicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
            }
            self.showView.activityIndicatorView.color = self.textColor;
            self.showView.title = model.text;
            [self showIsAutomaticClose:NO];
        }else{
            switch (model.state) {
                case ShowViewState_Text:
                    [self showText:model.text isShowImage:NO image:nil];
                    break;
                case ShowViewState_Info:
                    [self showText:model.text isShowImage:YES image:self.infoImage];
                    break;
                case ShowViewState_Error:
                    [self showText:model.text isShowImage:YES image:self.errorImage];
                    break;
                case ShowViewState_Success:
                    [self showText:model.text isShowImage:YES image:self.successImage];
                    break;
                default:
                    break;
            }
        }
        if (showTimer) {
            [showTimer invalidate];
            showTimer = nil;
        }
       
        if (self.showViewChangedBlock) {
            self.showViewChangedBlock(self.showState);
        }
        [showArray removeObjectAtIndex:0];
        showTimer = [NSTimer scheduledTimerWithTimeInterval:self.lineUpInterval target:self selector:@selector(show) userInfo:nil repeats:NO];
    }else{
        if (self.showLastBlock) {
            self.showLastBlock(self.showState);
        }
        _showState = ShowViewState_Nothing;
        self.isShowing = NO;
        if (showTimer) {
            [showTimer invalidate];
            showTimer = nil;
        }
    }
}

-(void)showText:(NSString *)text isShowImage:(BOOL)isShowImg image:(UIImage *)image{
    self.showView.spacing = 5;
    if (!CGSizeEqualToSize(self.showMinSizeWithoutLoading, CGSizeZero)) {
        self.showView.minSize = self.showMinSizeWithoutLoading;
    }
    self.showView.isLoading = NO;
    if (isShowImg) {
        self.showView.infoImageSize = CGSizeMake(22, 22);
    }else{
        self.showView.infoImageSize = CGSizeZero;
    }
    self.showView.defaultImage = image;
    self.showView.title = text;
    [self showIsAutomaticClose:self.isAutomaticClose];
}
-(void)updateShowViewCenter{
    float centerY = self.contentView.frame.size.height/2.;
    if (keyboardIsShow) {
        centerY = (self.contentView.frame.size.height - keyboardHeight)/2.;
    }
    self.showView.center = CGPointMake(self.contentView.frame.size.width/2., centerY);
}
-(void)showIsAutomaticClose:(BOOL)isClose{
    [self.contentView.layer removeAllAnimations];
    [[UIApplication sharedApplication].keyWindow addSubview:self.contentView];
    self.showView.alpha = 0.8;
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        self.showView.alpha = 1.;
        self.contentView.alpha = 1.;
        [self updateShowViewCenter];
    } completion:nil];
    if (dismissTimer) {
        [dismissTimer invalidate];
        dismissTimer = nil;
    }
    if (isClose) {
        dismissTimer = [NSTimer scheduledTimerWithTimeInterval:self.dismissInterval target:self selector:@selector(dismiss) userInfo:nil repeats:NO];
    }
    self.isShowing = YES;
}
-(void)appendShowData:(ZZProgressHUDModel *)showModel{
    if (!showArray) {
        showArray = [[NSMutableArray alloc] init];
    }
    if (!self.isLineUpShow) {
        self.isShowing = NO;
        [showArray removeAllObjects];
    }
    [showArray addObject:showModel];
    if (self.isShowing) return;
    [self show];
}
-(void)dismiss{
    [showArray removeAllObjects];
    self.isShowing = NO;
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        self.contentView.alpha = 0.;
    } completion:^(BOOL finished) {
        if (finished) {
            [self.contentView removeFromSuperview];
            if (self.dismissBlock) {
                self.dismissBlock();
            }
            self->_showState = ShowViewState_Nothing;
        }
    }];
}
+(void)dismiss{
    [[ZZProgressHUD shareZZProgressHUD] dismiss];
}
+(void)loading{
    [self loadingWithText:nil];
}
+(void)loadingWithText:(NSString *)text{
    ZZProgressHUDModel *model = [[ZZProgressHUDModel alloc] init];
    model.text = text;
    model.state = ShowViewState_Loading;
    [[ZZProgressHUD shareZZProgressHUD] appendShowData:model];
}
+(void)showText:(NSString *)text{
    ZZProgressHUDModel *model = [[ZZProgressHUDModel alloc] init];
    model.text = text;
    model.state = ShowViewState_Text;
    [[ZZProgressHUD shareZZProgressHUD] appendShowData:model];
}
+(void)showInfoWithText:(NSString *)text{
    ZZProgressHUDModel *model = [[ZZProgressHUDModel alloc] init];
    model.text = text;
    model.state = ShowViewState_Info;
    [[ZZProgressHUD shareZZProgressHUD] appendShowData:model];
}
+(void)showErrorWithText:(NSString *)error{
    ZZProgressHUDModel *model = [[ZZProgressHUDModel alloc] init];
    model.text = error;
    model.state = ShowViewState_Error;
    [[ZZProgressHUD shareZZProgressHUD] appendShowData:model];
}

+(void)showSuccessWithText:(NSString *)success{
    ZZProgressHUDModel *model = [[ZZProgressHUDModel alloc] init];
    model.text = success;
    model.state = ShowViewState_Success;
    [[ZZProgressHUD shareZZProgressHUD] appendShowData:model];
}
@end
